function [v n tt_vtl]= comp_agg(test, from, to,delta_t)
% It compute the weighted average, average, and N.N. interpolation values
% for each interval of length 'delta_t' (in sec) for the travel times 
% between 'from' and 'to' on 'test' day.

if to-from<7
    thr=300;
else
    thr=600;
end

[tt_vtl]= tt_between_vtl(test,from,to,'sparse',thr);

tt_vtl(:,1)=tt_vtl(:,1) + tt_vtl(:,2);
tt_vtl = sortrows(tt_vtl,1);

int = [53000:delta_t:62000]';

N = length(int);

for i=2:N
    % select the data from tt_vtl collected during the i-th interval
    [data_selected n(i,1)] = data_sel(delta_t,int(i,1),tt_vtl);
    
    % compute the weighted average using the data obtained before
    time = max(int(1,1),int(i,1)-delta_t);
    v(i,1) = w_avg(data_selected,time);
    
    % compute the average
    v(i,2) = mean(data_selected(:,2));    
    
    % N.N. interpolation
    dif=int(i,1)-tt_vtl(:,1); 
    [w e]=min(abs(dif)); 
    v(i,3)=tt_vtl(e,2); 
    
    v(i,4) = v(i,1);
    if isnan(v(i,1))
        v(i,4) = v(i,3);
    end
end

figure
hold on;
plot(tt_vtl(:,1),tt_vtl(:,2),'.--g')
plot(int(2:end),v(2:end,1),'s--')
plot(int(2:end),v(2:end,2),'^--k')
plot(int(2:end),v(2:end,3),'o--r') 
%plot(int(2:end),v(2:end,4),'d--c') 
axis([53000 62000 0 100])
axis 'auto y'

return;


% this function selects the rows in tt array to be considered in the
% weighted average
function [data_selected n] = data_sel(delta_t,time,tt)
% time: time at which the estimate is needed
% tt: data array obtained from tt_between_vtl

first_row = find(tt(:,1)-time+delta_t>0,1,'first');
last_row = find(tt(:,1)-time>0,1,'first') - 1;

data_selected = tt(first_row:last_row,:);
[n m]= size(data_selected);

% this function computes the weighted average on the data stored in
% data_selected
function wa = w_avg(data_selected,T1)

if isempty(data_selected)
    wa = NaN;
else
%    wa = mean(data_selected(:,2));
    weight = data_selected(:,1) - T1;
    num = sum(weight .* data_selected(:,2));
    den = sum(weight);
    wa = num / den;
end